﻿<template>
  <div :id = 'id' :class = 'className'></div>
</template>

<script>
import * as $echarts from 'echarts'
export default {
  props: {
    id: {
      type: String
    },
    className: {
      type: String
    },
    option: {
      type: Object
    }
  },
  data () {
    return {
      echart: ''
    }
  },
  watch: {
    option: {
      handler: function (newVal, oldVal) {
        if (this.echart) {
          if (newVal) {
            this.$nextTick(() => {
              this.echart.setOption(newVal, true)
            })
          } else {
            this.$nextTick(() => {
              this.echart.setOption(oldVal, true)
            })
          }
        } else {
          this.$nextTick(() => {
            this.echart.setOption(this.option, true)
          })
        }
      },
      deep: true
    },
    '$store.state.isCollapse': {
      handler: function (val) {
        this.updateEchartsSize()
      },
      deep: true
    },
    '$store.state.updateSize': {
      handler: function (val) {
        this.updateEchartsSize()
      },
      deep: true
    }
  },
  methods: {
    init (options) {
      this.echart = $echarts.init(document.getElementById(this.id))
      this.echart.setOption(options)
      // echart图能够进行缩放
      window.addEventListener('resize', this.echart.resize)
    },
    updateEchartsSize () {
      if (!this.echart) {
        return
      }
      this.echart.resize()
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init(this.option)
    })
  }
}
</script>
